package com.ccteam.fluidmusic.utils.preference

import androidx.preference.PreferenceDataStore
import com.ccteam.fluidmusic.fluidmusic.core.SettingCore
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/5
 *
 * 基于DataStore的Preference设置组件的自定义存储区
 * 对于Preference来说，默认使用SharedPreference，但因存在安全性问题
 * 所以使用DataStore来代替SharedPreference
 * 在putXXX方法中，将线程切至IO线程进行IO操作（SettingCore代码中）
 * 而getXXX方法中，使用runBlocking执行同步方法（此操作会阻塞线程，但如果预先读取了数据，则可以避免长时间阻塞）（SettingCore代码中）
 *
 * 该类由Hilt管理
 */
class DataStorePreference @Inject constructor(
    private val settingCore: SettingCore
): PreferenceDataStore() {

    override fun putString(key: String, value: String?) {
        settingCore.putString(key,value)
    }

    override fun getString(key: String, defValue: String?): String? {
        return settingCore.getString(key,defValue)
    }

    override fun putInt(key: String, value: Int) {
        settingCore.putInt(key,value)
    }

    override fun getInt(key: String, defValue: Int): Int {
        return settingCore.getInt(key,defValue)
    }

    override fun putBoolean(key: String, value: Boolean) {
        settingCore.putBoolean(key,value)
    }

    override fun getBoolean(key: String, defValue: Boolean): Boolean {
        return settingCore.getBoolean(key,defValue)
    }

    override fun putFloat(key: String, value: Float) {
        settingCore.putFloat(key,value)
    }

    override fun getFloat(key: String, defValue: Float): Float {
        return settingCore.getFloat(key,defValue)
    }

    override fun putLong(key: String, value: Long) {
        settingCore.putLong(key,value)
    }

    override fun getLong(key: String, defValue: Long): Long {
        return settingCore.getLong(key,defValue)
    }

    override fun putStringSet(key: String, values: MutableSet<String>?) {
        settingCore.putStringSet(key,values)
    }

    override fun getStringSet(key: String, defValues: MutableSet<String>?): MutableSet<String> {
        return settingCore.getStringSet(key,defValues)
    }

}